package com.brillilab.starter.controller.aio.space;

import com.brillilab.common.constant.ResultEnum;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.common.exceptions.BrillilabException;
import com.brillilab.domain.enums.common.IsDeleteEnum;
import com.brillilab.domain.enums.lab.LabMemberPowerEnum;
import com.brillilab.domain.po.lab.Lab;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.space.Device;
import com.brillilab.domain.po.space.Panel;
import com.brillilab.domain.po.user.Users;
import com.brillilab.domain.vo.space.DeviceWithPanelInfoVo;
import com.brillilab.domain.vo.space.PanelMerge;
import com.brillilab.domain.vo.space.PanelModify;
import com.brillilab.domain.vo.space.PanelVo;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.lab.ILabService;
import com.brillilab.service.core.space.IDeviceService;
import com.brillilab.service.core.space.IPanelService;
import com.brillilab.service.core.system.IDictService;
import com.brillilab.service.logic.space.PanelLogic;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.service.module.message.producer.MessageProducer;
import com.brillilab.service.module.message.template.impl.space.PlaneModifyToPrivateTemp;
import com.brillilab.service.module.message.template.impl.space.PrivatePlaneModifyTemp;
import com.brillilab.service.module.message.template.impl.space.PrivatePlaneModifyToPrivateTemp;
import com.brillilab.starter.aspect.AspectLog;
import com.brillilab.starter.constant.StarterConstant;
import com.brillilab.starter.handler.RequestPower;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wuzhiyu
 * @Title: Panel
 * @ProjectName brill_lab
 * @Description: TODO
 * @date 2018/11/139:28
 */
@RestController
@RequestMapping("/api/spaceManage/panel")
public class PanelController {
    @Autowired
    private IPanelService panelService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private UsersLogic usersLogic;
    @Autowired
    private PanelLogic panelLogic;
    @Autowired
    private IDictService dictService;
    @Resource
    private ILabService labService;
    @Resource
    private ILabMemberService labMemberService;
    @Resource
    private MessageProducer messageProducer;

    @AspectLog
    @PutMapping("/edit")
    @RequestPower(value = LabMemberPowerEnum.reagent)
    public ResponseVo edit(@RequestBody PanelModify panelModify, @RequestHeader(value = StarterConstant.TOKEN) String token) {
        if (StringUtils.isBlank(token)) {
            throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
        }
        Assert.notNull(panelModify, "data is null");
        Assert.notNull(panelModify.getId(), "panelId is null");
        UserInfoVo info = usersLogic.getUserByToken(token);
        Panel panel = panelService.get(panelModify.getId());

        Long oldLabMemberId = panel.getLabMemberId();//原平面所有者Id

        Assert.notNull(panel, "平面不存在");
        Assert.isTrue(IsDeleteEnum.NO.getValue().equals(panel.getIsDelete()), "平面不存在");
        if ((!panel.getLabId().equals(info.getLabId())) || panel.getIsDelete().equals(1)) {
            throw new BrillilabException(ResultEnum.USER_NOT_POWER);
        }
        panel.setRemark(panelModify.getRemark());
        panel.setUserReagentType(panelModify.getReagentTypes());
        panel.setLabMemberId(panelModify.getLabMemberId());

        boolean update = panelLogic.update(panel, panelModify.getIsChangeAll());
        if (update) {
            //修改成功，执行消息推送
            LabMember oldLabMember = labMemberService.selectById(oldLabMemberId);
            Lab lab=labService.selectById(panel.getLabId());
            LabMember currentMember = null;
            if (panel.getLabMemberId() != null) {
                currentMember = labMemberService.selectById(panel.getLabMemberId());
            }
            if(oldLabMember!=null){
                if(currentMember==null){
                    //当前所有者为空，执行私有变公共推送
                    //私有平面被修改成功为-公用(通知原所有者)
                    if(!info.getId().equals(oldLabMember.getUserId())) {
                        PrivatePlaneModifyTemp privatePlaneModifyTemp = new PrivatePlaneModifyTemp(panel.getLabId(), oldLabMember.getUserId(), oldLabMemberId, lab.getName(), panel.getDeviceIndex(), panel.getName());
                        messageProducer.sendMessagePush(privatePlaneModifyTemp);
                    }
                }
                else {
                    if (!oldLabMember.getUserId().equals(currentMember.getUserId())) {
                        //推送—>被修改用户（通知被修改人）
                        if(!info.getId().equals(oldLabMember.getUserId())) {
                            Users newUser = usersLogic.getUser(currentMember.getUserId());
                            PrivatePlaneModifyToPrivateTemp privatePlaneModifyToPrivateTemp = new PrivatePlaneModifyToPrivateTemp(panel.getLabId(), oldLabMember.getUserId(), oldLabMemberId, lab.getName(), panel.getDeviceIndex(), panel.getName(), newUser.getName());
                            messageProducer.sendMessagePush(privatePlaneModifyToPrivateTemp);
                        }

                        //推送—>修改后的用户(通知当前所有者)
                        if(!info.getId().equals(currentMember.getUserId())) {
                            PlaneModifyToPrivateTemp planeModifyToPrivateTemp = new PlaneModifyToPrivateTemp(panel.getLabId(), currentMember.getUserId(), panel.getLabMemberId(), lab.getName(), panel.getDeviceIndex(), panel.getName(), info.getName());
                            messageProducer.sendMessagePush(planeModifyToPrivateTemp);
                        }
                    }
                }
            }else{
                if (currentMember != null && !info.getId().equals(currentMember.getUserId())) {
                    //推送—>修改后的用户(通知当前所有者)
                    PlaneModifyToPrivateTemp planeModifyToPrivateTemp = new PlaneModifyToPrivateTemp(panel.getLabId(), currentMember.getUserId(), panel.getLabMemberId(), lab.getName(), panel.getDeviceIndex(), panel.getName(), info.getName());
                    messageProducer.sendMessagePush(planeModifyToPrivateTemp);
                }
            }
        }

        return update ? ResponseVo.success() : ResponseVo.failure();
    }

    @GetMapping("/panelList")
    public ResponseVo panelList(Long deviceId, @RequestHeader(value = StarterConstant.TOKEN) String token) {
        Assert.notNull(deviceId, "deviceId is null");
        Device device = deviceService.get(deviceId);
        UserInfoVo info = usersLogic.getUserByToken(token);
        DeviceWithPanelInfoVo dp = panelLogic.getPanelList(deviceId, info);
        return ResponseVo.success(dp);
    }

    @AspectLog
    @PostMapping("/merge")
    @RequestPower(value = LabMemberPowerEnum.reagent)
    public ResponseVo merge(@RequestBody PanelMerge panelMerge, @RequestHeader(value = StarterConstant.TOKEN) String token) {
        if (StringUtils.isBlank(token)) {
            throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
        }
        Assert.notNull(panelMerge, "data is null");
        Assert.isTrue(!CollectionUtils.isEmpty(panelMerge.getUpdateList()) || !CollectionUtils.isEmpty(panelMerge.getDelList()), "data is empty");
        Assert.isTrue(panelMerge.getAddList().size() > 0 || panelMerge.getDelList().size() > 0, "数据错误");
        UserInfoVo info = usersLogic.getUserByToken(token);
        return panelLogic.merge(panelMerge, info) ? ResponseVo.success() : ResponseVo.failure();
    }

    @GetMapping("/get")
    public ResponseVo get(Long panelId, @RequestHeader(value = StarterConstant.TOKEN) String token) {
        Assert.notNull(panelId, "data is null");
        Panel panel = panelService.get(panelId);
        Assert.notNull(panel, "平面不存在");
        Assert.isTrue(IsDeleteEnum.NO.getValue().equals(panel.getIsDelete()), "平面不存在");
        UserInfoVo info = usersLogic.getUserByToken(token);
        Assert.isTrue(panel.getLabId().equals(info.getLabId()), "平面不存在");
        PanelVo panelVo = panelLogic.getPanel(panel);
        return ResponseVo.success(panelVo);
    }


    //@Deprecated
    //@PostMapping("/addList")
    //@RequestPower(LabMemberPowerEnum.reagent)
    //public ResponseVo addList(@RequestBody List<PanelAdd> panelAddList, @RequestHeader(value = StarterConstant.TOKEN) String token) {
    //    if (StringUtils.isBlank(token)) {
    //        throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
    //    }
    //    Assert.notNull(panelAddList, "data is null");
    //    Assert.isTrue(panelAddList.size() > 0, "panelList is empty");
    //    Device device = deviceService.get(panelAddList.get(0).getDeviceId());
    //    Assert.notNull(device, "data not exist");
    //    UserInfoVo info = usersLogic.getUserByToken(token);
    //    if ((!device.getLabId().equals(info.getLabId())) || device.getIsDelete().equals(1)) {
    //        throw new BrillilabException(ResultEnum.USER_NOT_POWER);
    //    }
    //    List<Panel> dbList = panelService.getPanelList(device.getId());
    //    List<Panel> panelList = new ArrayList<>();
    //    panelAddList.forEach(panelAdd -> {
    //        if(dbList.stream().filter(d->d.getName().equals(panelAdd.getName())).count()>0){
    //            throw  new BrillilabException(ResultEnum.DATA_ALREADY_EXIST);
    //        }
    //        Panel panel = new Panel();
    //        panel.setZone(device.getZone());
    //        panel.setRoomName(device.getRoomName());
    //        panel.setRoomId(device.getRoomId());
    //        panel.setLabId(device.getLabId());
    //        panel.setIsDelete(0);
    //        panel.setDeviceIndex(device.getDeviceIndex());
    //        panel.setDeviceId(device.getId());
    //        panel.setColumns(panelAdd.getColumns());
    //        panel.setRows(panelAdd.getRows());
    //        panel.setHeight(panelAdd.getHeight());
    //        panel.setWidth(panelAdd.getWidth());
    //        panel.setX(panelAdd.getX());
    //        panel.setY(panelAdd.getY());
    //        panel.setName(panelAdd.getName());
    //        panel.setRemark(panelAdd.getRemark());
    //        panel.setUserReagentType(panelAdd.getReagentTypes());
    //        panel.setLabMemberId(panelAdd.getLabMemberId());
    //        panelList.save(panel);
    //    });
    //    return panelService.addList(panelList) ? ResponseVo.success() : ResponseVo.failure();
    //}
    //@Deprecated
    @DeleteMapping("/deleteList")
    @RequestPower(LabMemberPowerEnum.reagent)
    public ResponseVo deleteList(@RequestBody List<Long> idList, @RequestHeader(value = StarterConstant.TOKEN) String token) {
        if (StringUtils.isBlank(token)) {
            throw new BrillilabException(ResultEnum.USER_NOT_LOGIN);
        }
        Assert.notNull(idList, "data is null");
        Assert.isTrue(idList.size() > 0, "data is empty");
        UserInfoVo info = usersLogic.getUserByToken(token);
        idList.forEach(o -> {
            Panel panel = panelService.get(o);
            Assert.notNull(panel, "data not exist");
            if (!panel.getLabId().equals(info.getLabId())) {
                throw new BrillilabException(ResultEnum.USER_NOT_POWER);
            }
        });
        return panelLogic.deleteList(idList) ? ResponseVo.success() : ResponseVo.failure();
    }
}
